package middleware

import (
	"api/internal/types"
	"api/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type UserLoginMiddleware struct {
}

func NewUserLoginMiddleware() *UserLoginMiddleware {
	return &UserLoginMiddleware{}
}

func (m *UserLoginMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Msg:  "当前未登录",
				Code: "500",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		data, claims := pkg.GetTokenData(token)
		if data != "" {
			resp := types.Response{
				Msg:  data,
				Code: "500",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		id := claims["id"].(string)
		r.ParseForm()
		r.Form.Set("id", id)
		next(w, r)
	}
}
